import React, { Fragment } from 'react'
import { StyleSheet, ScrollView, View, Text } from 'react-native'
import { ScaleS, ScaleT, ONE_PIXEL, WIDTH } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import { connect } from 'react-redux'
import { liveApplyUpList, liveCollectionList, getLivePostList } from 'src/utils/RequestAPI'
import { getSettlementMethod, getUserAvatorLocalB, unitList, getDistance } from 'src/utils/ConfigUtil'
import { formatTime, todayYestodayTime, utilToKilo } from 'src/utils/TimeUtil'
import LiveList from 'src/components/live-list/LiveList'
import CustomButton from 'src/components/button/CustomButton'
import DefaultImage from 'src/components/image/DefaultImage'
import CustomTextEllipsize from 'src/components/custom-text-ellipsize/index'
import EmptyView from '../../../components/empty-view/index'
import { TabView } from 'react-native-tab-view'
import CustomFlatList from 'src/components/custom-flat-list/index'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import NavigationUtil from 'src/utils/NavigationUtil'
import { DismissLoading, ShowLoading } from 'src/utils/ToastUtil'
import { generateFuzzyQuery } from 'src/utils/FuzzyQueryUtil'
import CustomImage from 'src/components/image/CustomImage'

const routes = [
  { key: 'subscribe', title: '直播预约' },
  { key: 'collection', title: '直播收藏' },
  { key: 'resume', title: '已投简历' }
]
@connect(
  ({ userinfo, landmark }) => ({
    userId: userinfo.userId,
    landmark
  })
)
class LiveSubscribe extends BasePage {
  constructor (props) {
    super(props)
    const {
      navigation: {
        state: { params = {} } = {}
      }
    } = props
    this.state = {
      header: {},
      liveDataSubscribe: [],
      liveDataCollection: [],
      liveDataResume: [],
      headerTitle: '',
      index: params.liveIndex,
      routes: routes,
      limit: 999
    }
    this.pageIndex = [1, 1, 1]
    this.flatListRef = []
    this.params = params
  }

  componentDidMount () {
  }

  componentWillUnmount () {
  }

  componentWillFocus () {
    this._initData()
  }

  _initData = () => {
    ShowLoading()
    const { limit } = this.state
    Promise.all([
      liveApplyUpList({ params: { limit, page: this.pageIndex[0] } }),
      liveCollectionList({ params: { limit, page: this.pageIndex[1] } }),
      getLivePostList({ params: { limit, page: this.pageIndex[2] } })
    ]).finally(([{ data: liveDataSubscribe }, { data: liveDataCollection }, { data: liveDataResume }]) => {
      DismissLoading()
      this.setState({
        liveDataSubscribe,
        liveDataCollection,
        liveDataResume
      })
    })
  }

  childRender () {
    return (
      <View style={styles.container}>
        <TabView
          style={styles.tabView}
          navigationState={this.state}
          renderScene={this._renderScene}
          onIndexChange={this._onIndexChange}
          renderTabBar={this._renderTabBar}
          initialLayout={{
            height: 0,
            width: WIDTH
          }}
        />
      </View>
    )
  }

  /**
   * 渲染每一个屏
   * @param route
   * @param jumpTo
   * @returns {*}
   * @private
   */
  _renderScene = (params) => {
    const { route: { key } } = params
    const { liveDataSubscribe, liveDataCollection, liveDataResume } = this.state
    switch (key) {
      case routes[0].key:
        return this._renderPageComponent(0, key, liveDataSubscribe)
      case routes[1].key:
        return this._renderPageComponent(1, key, liveDataCollection)
      case routes[2].key:
        return this._renderPageComponent(2, key, liveDataResume)
    }
  }

  _renderPageComponent = (index, key, data) => {
    return <CustomFlatList
      ref={this._flatListRef}
      index={index}
      style={styles.flatList}
      renderItem={key === 'resume' ? this.renderItemResume : this.renderItem}
      data={data}
      keyExtractor={this._keyExtractor}
      pullDown={false}
      pullUp={false}
      ListEmptyComponent={this._listEmptyComponent()}
      showsVerticalScrollIndicator={false}
    />
  }

  renderItem = ({ item, index }) => {
    if (item) {
      return <View style={{ paddingHorizontal: ScaleS(20) }}>
        <LiveList liveData={item} type='LiveSubscribe' />
      </View>
    } else {
      return null
    }
  }

  renderItemResume = ({ item, index }) => {
    return <View style={styles.livePostContainer}>
      <View style={styles.topContainer}>
        <View style={styles.postRight}>
          <Text style={styles.postRightTitle}>{item.name}</Text>
          <Text style={styles.postRightPublisher}>{`主讲：${item.publisher}`}</Text>
        </View>
        <DefaultImage
          style={styles.postImg} source={{ uri: item.logo }}
          errorSource={getUserAvatorLocalB()} />
      </View>
      {
        item.posts.map((itemPost, indexPost) => {
          return this._renderJobCell(itemPost, indexPost)
        })
      }
    </View>
  }

  _listEmptyComponent = () => {
    return (
      <EmptyView emptyImg={require('src/imgC/home/home_no_data.png')} style={styles.emptyView} firstTip={'暂无相关数据'}/>
    )
  }

  _flatListRef = (ref) => {
    if (ref && ref.props) {
      const { index } = ref.props
      this.flatListRef[index] = ref
    }
  }

  _keyExtractor = (item) => {
    return (item.id || item.channelId).toString()
  }

  /**
   * 切换标签
   * @param index
   * @private
   */
  _onIndexChange = (index) => {
    this.setState({ index })
  }

  _setEndRefreshingState = (data) => {
    if (data && data.length > 9) {
      this._setEndRefreshState(RefreshState.CanLoadMore)
    } else {
      this._setEndRefreshState(RefreshState.NoMoreData)
    }
  }

  _setEndRefreshState = (state) => {
    const { index } = this.state
    this.flatListRef[index].endRefreshing(state)
  }

  _renderTabBar = (props) => {
    const { index } = this.state
    return (
      <View style={styles.tabContainer}>
        <CustomButton style={[styles.tabItem, index === 0 && styles.tabItemActive]} onPress={this._tabBarClick} params={{ props, key: routes[0].key }}>
          <Text style={[styles.tabItemText, index === 0 && styles.tabItemTextActive]}>{routes[0].title}</Text>
        </CustomButton>
        <CustomButton style={[styles.tabItem, index === 1 && styles.tabItemActive]} onPress={this._tabBarClick} params={{ props, key: routes[1].key }}>
          <Text style={[styles.tabItemText, index === 1 && styles.tabItemTextActive]}>{routes[1].title}</Text>
        </CustomButton>
        <CustomButton style={[styles.tabItem, index === 2 && styles.tabItemActive]} onPress={this._tabBarClick} params={{ props, key: routes[2].key }}>
          <Text style={[styles.tabItemText, index === 2 && styles.tabItemTextActive]}>{routes[2].title}</Text>
        </CustomButton>
      </View>
    )
  }

  _tabBarClick = ({ props, key }) => {
    const { jumpTo } = props
    jumpTo(key)
  }

  // renderNavigationBarChild () {
  //   const { headerTitle } = this.state
  //   return (
  //     <Fragment>
  //       <Text style={styles.navigationTitle}>{headerTitle}</Text>
  //     </Fragment>
  //   )
  // }

  _jobClick = ({ item, index }) => {
    NavigationUtil.navigate('CJobdetail', {
      id: item.id,
      isLivePost: true,
      cityName: this.props.landmark.cityName
    })
  }

  resumeStateView = (state) => {
    // 投递情况 未处理 不合适，直接录用 初试 二面 三面 四面"
    switch (state) {
      case '未处理':
      case '初试':
      case '二面':
      case '三面':
      case '四面':
        return <Text style={styles.bottomRight}>{state}</Text>
      case '不合适':
        return <CustomImage
          style={styles.stateImg}
          source={require('@/imgC/live/resume_icon_no.png')}
        />
      case '直接录用':
        return <CustomImage
          style={styles.stateImg}
          source={require('@/imgC/live/resume_icon_pass.png')}
        />
      default:
        return <Text style={styles.bottomRight}>{state}</Text>
    }
  }

  // jobcell
  _renderJobCell = (item, index) => {
    const basicInfoModel = item.basicInfoModel
    const settlementMethodObj = item && item.basicInfoModel ? getSettlementMethod(item.basicInfoModel.settlementMethod) : {}
    const unit = item && item.basicInfoModel ? unitList[item.basicInfoModel.unit ? item.basicInfoModel.unit : item.basicInfoModel.settlementMethod * 1 + 1] : {}
    const { bossInfo = {} } = item
    return <CustomButton
      style={styles.cellContainer}
      onPress={this._jobClick}
      key={item.id || index}
      params={{ item, index }}
    >
      <View style={styles.bottomView}>
        <View style={styles.top}>
          <View style={styles.topLeft}>
            <CustomTextEllipsize style={styles.name} text={item.basicInfoModel.name} />
            {
              parseInt(item.isFast) === 1 && (
                <View style={styles.fastView}>
                  <View style={styles.fastBgView} />
                  <Text style={styles.fastText}>顶</Text>
                </View>
              )
            }
          </View>
          <View style={styles.salaryView}>
            <Text style={styles.price}>
              {`${utilToKilo(item.basicInfoModel.salary)}${item.basicInfoModel.salary >= 10000 ? '' : '元'}·${unit}`}
            </Text>
          </View>
        </View>
        <View style={styles.bottom}>
          <View style={styles.bottomLeft}>
            {item.area && <Text style={styles.tagItemText}>{'#' + item.area}</Text>}
            <Text style={styles.tagItemText}>{'#' + basicInfoModel.category}</Text>
            <Text style={styles.tagItemText}>{'#' + settlementMethodObj.short}</Text>
          </View>
          {this.resumeStateView(item.sendState)}
        </View>
      </View>
      <View style={styles.collectBossInfo}>
        <View style={styles.collectBossInfoLeft}>
          <DefaultImage
            style={styles.collectImg} source={{ uri: bossInfo.headImg }}
            errorSource={getUserAvatorLocalB()} />
          <Text style={styles.collectName}>{bossInfo.userName}</Text>
        </View>
        {!!item.gmtCreate && (
          <Text
            style={styles.collectDate}>{todayYestodayTime(new Date(formatTime(item.gmtCreate)).getTime())}</Text>
        )}
      </View>
    </CustomButton>
  }
}

export default LiveSubscribe

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  flatList: {
    flexDirection: 'column'
  },
  tabView: {
  },
  livePostContainer: {
    paddingTop: ScaleS(6),
    backgroundColor: '#F7F7F7'
  },
  tabContainer: {
    width: WIDTH,
    height: ScaleS(50),
    paddingHorizontal: ScaleS(20),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  tabItem: {
    paddingVertical: ScaleS(8),
    paddingHorizontal: ScaleS(16),
    backgroundColor: '#fff',
    borderRadius: ScaleS(16)
  },
  tabItemActive: {
    backgroundColor: '#FFE400'
  },
  tabItemText: {
    fontSize: ScaleT(13),
    fontWeight: '400',
    color: '#CCCCCC'
  },
  tabItemTextActive: {
    color: '#3C3C3C',
    fontWeight: '500'
  },
  topContainer: {
    paddingHorizontal: ScaleS(20),
    paddingTop: ScaleS(30),
    paddingBottom: ScaleS(20),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: '#fff'
  },
  postRight: {},
  postRightTitle: {
    color: '#3C3C3C',
    fontSize: ScaleT(14),
    fontWeight: '500',
    marginBottom: ScaleS(11)
  },
  postRightPublisher: {
    fontSize: ScaleT(12),
    fontWeight: '500',
    color: '#CCCCCC'
  },
  cellContainer: {
    paddingHorizontal: ScaleS(20),
    paddingTop: ScaleS(29),
    paddingBottom: ScaleS(20),
    borderTopColor: 'rgba(151, 151, 151, 0.25)',
    borderTopWidth: ONE_PIXEL,
    borderStyle: 'solid',
    backgroundColor: '#fff'
  },
  postImg: {
    width: ScaleS(48),
    height: ScaleS(48),
    resizeMode: 'cover',
    borderRadius: ScaleS(10)
  },
  bottomView: {
    marginBottom: ScaleS(26)
  },
  top: {
    flexDirection: 'row',
    alignItems: 'flex-start'
  },
  topLeft: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center'
  },
  name: {
    width: ScaleS(180),
    fontSize: ScaleT(16),
    fontWeight: '500',
    color: '#3c3c3c'
  },
  fastView: {
    marginLeft: ScaleS(8),
    alignItems: 'center',
    justifyContent: 'center'
  },
  fastBgView: {
    backgroundColor: '#FFE400',
    width: ScaleS(23),
    height: ScaleS(4)
  },
  fastText: {
    color: '#000000',
    fontSize: ScaleT(12),
    fontWeight: '500',
    position: 'absolute'
  },
  salaryView: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  price: {
    textAlign: 'right',
    fontSize: ScaleT(16),
    fontWeight: '500',
    color: '#FADE25',
    marginLeft: ScaleS(20)
  },
  unit: {
    fontSize: ScaleT(16),
    fontWeight: '500',
    color: '#FADE25'
  },
  tagItemText: {
    color: '#bdbdbd',
    fontSize: ScaleT(14),
    fontWeight: '400',
    marginRight: ScaleS(15)
  },
  bottom: {
    marginTop: ScaleS(10),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  bottomLeft: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'flex-start',
    flexWrap: 'wrap'
  },
  collectBossInfo: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  collectBossInfoLeft: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  collectImg: {
    width: ScaleS(25),
    height: ScaleS(25),
    resizeMode: 'cover',
    marginRight: ScaleS(6),
    borderRadius: ScaleS(13)
  },
  collectName: {
    fontSize: ScaleT(12),
    color: '#999999',
    fontWeight: '400'
  },
  collectDate: {
    fontSize: ScaleT(12),
    color: '#CCCCCC'
  },
  bottomRight: {
    fontSize: ScaleT(14),
    color: '#666666'
  },
  stateImg: {
    position: 'absolute',
    top: 0,
    right: 0,
    width: ScaleS(82),
    height: ScaleS(82)
  }
})
